package com.bondar.task5;

import java.util.ArrayList;
import java.util.concurrent.atomic.AtomicInteger;

public class BankWithLock {

	private final ArrayList<AccountWithLock> accounts;
	private AtomicInteger failedTransfers;
	
	public BankWithLock() {
		accounts = new ArrayList<AccountWithLock>();
		failedTransfers = new AtomicInteger();
	}

	public void transfer(AccountWithLock from, AccountWithLock to, int amount) {
		from.getLock().lock();
		
		try {
			while (!to.getLock().tryLock());
			
			try {
				if (from.withdraw(amount)) {
					to.deposit(amount);
				} else {
					failedTransfers.incrementAndGet();
				}
			} finally {
				to.getLock().unlock();
			}
				
		} finally {
			from.getLock().unlock();
		}
	}

	public int getTotal() {
		int total = 0;
		for (int i = 0; i < accounts.size(); i++) {
			total += accounts.get(i).getBalance();
		}
		return total;
	}

	public void addAccount(AccountWithLock account) {
		accounts.add(account);
	}

	public int accounts() {
		return accounts.size();
	}

	public AccountWithLock getAccount(int nextInt) {
		return accounts.get(nextInt);
	}
	
	public int getFailedTransfers() {
		return failedTransfers.get();
	}
}
